<template>
  <div class="story-view">
    <div class="story-header">
      <button @click="goBack" class="refresh-btn back-btn">
        <span class="icon">&#8592;</span> 返回
      </button>

      <h2>⚡ 快速故事阅读</h2>
      <div class="button-container">
        <button @click="loadPreGeneratedStory" class="refresh-btn">
          <span class="icon">&#x1F4DA;</span> 获取预生成故事
        </button>
        <button @click="goToStory" class="generate-story-btn">
          <span class="icon">&#x1F4D6;</span> 生成故事
        </button>
        <button @click="restartCurrentStory" class="reset-btn" v-if="storyStarted">
          <span class="icon">&#x21BB;</span> 重新开始
        </button>
      </div>
    </div>
    
    <!-- 故事内容区域 -->
    <div v-if="displayLines.length">
      <!-- 场景图片区域 -->
      <div class="scene-image-container" v-if="sceneImage">
        <img :src="sceneImageUrl" class="scene-image" />
      </div>
      <div class="scene-image-placeholder" v-else-if="storyStarted">
        <div class="no-image-notice">故事情境想象中...</div>
      </div>
      
      <!-- 故事文本显示区域 -->
      <div class="dialogue-box">
        <div 
          v-for="(line, index) in displayLines" 
          :key="index" 
          class="story-line"
          v-html="highlightKeywords(line)"
        ></div>
        
        <!-- 添加中文翻译区域 -->
        <pre v-if="showTranslation && chineseTranslation" class="translation-text" v-html="highlightKeywords(chineseTranslation)"></pre>

        <!-- 选择按钮区域 -->
        <div v-if="choices.length > 0 && !isStoryEnding" class="choices-list">
          <h4>🎯 你的选择：</h4>
          <button
            v-for="(choice, idx) in choices"
            :key="idx"
            @click="selectChoice(idx)"
            class="choice-btn"
            :disabled="loading"
          >
            {{ idx + 1 }}. {{ choice }}
          </button>
        </div>

        <!-- 故事结束提示 -->
        <div v-if="isStoryEnding" class="story-ending">
          <span class="ending-icon">🏁</span> 故事已结束
          <button @click="restartCurrentStory" class="restart-btn">
            <span class="icon">🔄</span> 重新开始
          </button>
        </div>

        <!-- 页面导航控件 -->
        <div class="page-navigation" v-if="storyPages.length > 1">
          <button 
            @click="prevPage" 
            class="page-nav-btn" 
            :disabled="currentPageIndex === 0"
            type="button"
          >
            <span class="icon">&#x2190;</span> 上一页
          </button>
          <div class="page-indicator">{{ currentPageIndex + 1 }}/{{ storyPages.length }}</div>
          <button 
            @click="nextPage" 
            class="page-nav-btn" 
            :disabled="currentPageIndex >= storyPages.length - 1"
            type="button"
          >
            下一页 <span class="icon">&#x2192;</span>
          </button>
        </div>
        
        <!-- 添加翻译切换按钮 -->
        <button @click="toggleTranslation" class="translation-btn" v-if="storyStarted">
          <span class="icon">🔤</span> {{ showTranslation ? '隐藏翻译' : '显示翻译' }}
        </button>
        
        <!-- 英文语音播放按钮 -->
        <button @click="playEnglishSpeech" class="speech-btn" v-if="storyStarted">
          <span class="icon">{{ isSpeaking ? '⏸️' : '🔊' }}</span> 
          {{ isSpeaking ? '暂停语音' : '播放英文语音' }}
        </button>
      </div>
    </div>
    
    <div v-else-if="!loading" class="no-story">
      <div class="welcome-message">
        <h3>欢迎来到快速故事阅读！</h3>
        <p>系统已为您预生成个性化故事，点击按钮即可开始</p>
        <p>故事内容基于您的学习单词，阅读更有针对性</p>
      </div>
    </div>
    
    <!-- 加载状态覆盖层 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading">
        <span class="spinner"></span> 
        <span>{{ loadingMessage }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request.js";

export default {
  name: "FastStory",
  
  data() {
    return {
      loading: false,
      loadingMessage: "故事加载中...",
      displayLines: [],
      chineseTranslation: "",
      choices: [],
      keywords: [],
      
      // 故事相关数据
      storyStarted: false,
      isStoryEnding: false,
      sceneImage: null,
      
      // 修改：支持多页面的数据结构
      storyPages: [],           // 存储所有故事页面
      currentPageIndex: 0,      // 当前页面索引
      
      // 预生成故事相关
      templateId: null,
      userProgress: null,
      
      // 控制中文翻译显示/隐藏
      showTranslation: false,   // 是否显示中文翻译
      isSpeaking: false,        // 添加语音播放状态
      
      // 恢复逐个词显示功能
      currentWordIndex: 0,      // 当前显示到第几个词
      allWords: [],             // 所有词汇数组
      isFullyDisplayed: false,  // 是否已完全显示
      typingSpeed: 150,         // 打字速度(ms)
      typingTimer: null,        // 打字计时器
    };
  },
  
  computed: {
    sceneImageUrl() {
      return this.sceneImage ? `data:image/png;base64,${this.sceneImage}` : '';
    },
    
    currentPage() {
      return this.storyPages[this.currentPageIndex] || {
        id: null,
        englishContent: "",
        chineseContent: "",
        sceneImageBase64: null,
        choices: [],
        isEnding: false
      };
    }
  },
    created() {
    // 检查是否有传递的模板ID
    if (this.$route.query.templateId) {
      console.log("检测到模板ID参数，加载指定故事:", this.$route.query.templateId);
      const templateId = parseInt(this.$route.query.templateId);
      this.templateId = templateId;
      this.loadSpecificStory(templateId);
    } else {
      console.log("没有模板ID参数，加载预生成故事");
      this.loadPreGeneratedStory();
    }
  },
  
  mounted() {
    this.addKeywordClickListener();
    // 添加空格键监听
    document.addEventListener('keydown', this.handleSpaceKey);
  },
  
  beforeDestroy() {
    // 清理事件监听和计时器
    document.removeEventListener('keydown', this.handleSpaceKey);
    if (this.typingTimer) {
      clearTimeout(this.typingTimer);
    }
    window.speechSynthesis.cancel();
  },
  
  updated() {
    this.addKeywordClickListener();
  },
  
  methods: {
    // 处理空格键事件
    handleSpaceKey(event) {
      if (event.code === 'Space' && this.storyStarted && !this.isFullyDisplayed) {
        event.preventDefault();
        this.showAllWords();
      }
    },
    
    // 开始逐个词显示
    startWordByWordDisplay(content) {
      if (!content) return;
      
      // 重置状态
      this.currentWordIndex = 0;
      this.isFullyDisplayed = false;
      this.allWords = content.split(/(\s+)/).filter(word => word.trim().length > 0);
      this.displayLines = [];
      
      // 清除之前的计时器
      if (this.typingTimer) {
        clearTimeout(this.typingTimer);
      }
      
      // 开始逐个词显示
      this.displayNextWord();
    },
    
    // 显示下一个词
    displayNextWord() {
      if (this.currentWordIndex < this.allWords.length && !this.isFullyDisplayed) {
        const word = this.allWords[this.currentWordIndex];
        
        // 构建当前显示的文本
        const currentText = this.allWords.slice(0, this.currentWordIndex + 1).join(' ');
        this.displayLines = [this.highlightKeywords(currentText)];
        
        this.currentWordIndex++;
        
        // 设置下一个词的显示
        this.typingTimer = setTimeout(() => {
          this.displayNextWord();
        }, this.typingSpeed);
      } else {
        // 全部显示完毕
        this.isFullyDisplayed = true;
        this.showAllWords();
      }
    },
    
    // 立即显示所有词
    showAllWords() {
      this.isFullyDisplayed = true;
      if (this.typingTimer) {
        clearTimeout(this.typingTimer);
      }
      
      const page = this.currentPage;
      if (page && page.englishContent) {
        this.displayLines = page.englishContent.split('\n').map(line => this.highlightKeywords(line));
      }
      
      this.addKeywordClickListener();
    },
    
    // 加载指定模板的故事
    async loadSpecificStory(templateId) {
      console.log("=== 开始加载指定故事 ===");
      console.log("模板ID:", templateId);
      
      this.loading = true;
      this.loadingMessage = "加载指定故事中...";
      
      try {
        let userJson = localStorage.getItem("user");
        if (!userJson) {
          this.$message.error("用户信息不存在，请重新登录");
          this.loadPreGeneratedStory();
          return;
        }
        
        let user = JSON.parse(userJson);
        
        if (!user.userID) {
          this.$message.error("用户ID不存在，请重新登录");
          this.loadPreGeneratedStory();
          return;
        }
        
        const response = await request.post("/api/story/load-specific", null, {
          params: { 
            userID: user.userID,
            templateId: templateId
          }
        });
        
        if (response && response.currentPage) {
          this.handleStoryData(response);
        } else {
          this.$message.error("加载指定故事失败");
          this.loadPreGeneratedStory();
        }
      } catch (error) {
        console.error("加载指定故事失败:", error);
        this.$message.error("加载故事失败，尝试加载默认故事");
        this.loadPreGeneratedStory();
      } finally {
        this.loading = false;
      }
    },

    // 提取公共的故事数据处理逻辑
    handleStoryData(res) {
      console.log("=== 开始处理故事数据 ===");
      
      if (res.pageHistory && res.pageHistory.length > 0) {
        this.storyPages = res.pageHistory.map(page => ({
          id: page.id,
          englishContent: page.englishContent,
          chineseContent: page.chineseContent,
          sceneImageBase64: page.sceneImageBase64,
          choices: page.choices || [],
          isEnding: page.isEnding || false
        }));
        this.currentPageIndex = res.currentPageIndex || (this.storyPages.length - 1);
      } else {
        this.storyPages = [{
          id: res.currentPage.id,
          englishContent: res.currentPage.englishContent,
          chineseContent: res.currentPage.chineseContent,
          sceneImageBase64: res.currentPage.sceneImageBase64,
          choices: res.currentPage.choices || [],
          isEnding: res.currentPage.isEnding || false
        }];
        this.currentPageIndex = 0;
      }
      
      this.templateId = res.template.id;
      this.userProgress = res.progress;
      this.keywords = res.keywords || [];
      this.storyStarted = true;
      this.isStoryEnding = res.currentPage.isEnding || false;
      
      // 更新显示（恢复逐词显示）
      this.updateDisplayContent();
      
      this.$message.success(`故事《${res.template.title}》加载成功！`);
    },
    
    // 更新显示内容（恢复逐词显示功能）
    updateDisplayContent() {
      const page = this.currentPage;
      
      // 同步更新其他显示内容
      this.chineseTranslation = page.chineseContent || "";
      this.sceneImage = page.sceneImageBase64 || null;
      this.choices = page.choices || [];
      
      // 开始逐个词显示
      if (page && page.englishContent) {
        this.startWordByWordDisplay(page.englishContent);
      } else {
        this.displayLines = [];
      }
      
      // 只有当前页面是最后一页且是结局时才显示结束
      this.isStoryEnding = (this.currentPageIndex === this.storyPages.length - 1) && page.isEnding;
    },
    
    restartCurrentStory() {
      if (!this.templateId) {
        this.$message.warning("没有正在进行的故事，请先获取故事");
        this.loadPreGeneratedStory();
        return;
      }
      
      this.resetStory();
      this.loading = true;
      this.loadingMessage = "重新开始故事中...";
      
      let userJson = localStorage.getItem("user");
      let user = JSON.parse(userJson);
      
      request.post("/api/story/restart", null, {
        params: { 
          userID: user.userID,
          templateId: this.templateId
        }
      })
      .then(res => {
        if (res && res.page) {
          this.storyPages = [{
            id: res.page.id,
            englishContent: res.page.englishContent,
            chineseContent: res.page.chineseContent,
            sceneImageBase64: res.page.sceneImageBase64,
            choices: res.page.choices || [],
            isEnding: res.page.isEnding || false
          }];
          
          this.currentPageIndex = 0;
          this.userProgress = res.progress;
          this.keywords = res.keywords || [];
          this.storyStarted = true;
          this.isStoryEnding = false;
          
          this.updateDisplayContent();
          this.$message.success(res.message || "故事重新开始！");
        } else {
          this.$message.error("重新开始失败，请重试");
        }
      })
      .catch(err => {
        console.error("重新开始故事失败", err);
        this.$message.error("重新开始失败，请检查网络连接");
      })
      .finally(() => {
        this.loading = false;
      });
    },
    
    goToStory() {
      this.$router.push('/story');
    },
    
    goBack() {
      this.$router.back();
    },
    
    toggleTranslation() {
      this.showTranslation = !this.showTranslation;
    },
    
    playEnglishSpeech() {
      if (this.isSpeaking) {
        window.speechSynthesis.cancel();
        this.isSpeaking = false;
      } else {
        const text = this.currentPage.englishContent || this.allWords.join(' ');
        if (!text) return;
        
        window.speechSynthesis.cancel();
        
        const utter = new window.SpeechSynthesisUtterance(text);
        utter.lang = 'en-US';
        utter.rate = 1.0;
        
        utter.onend = () => {
          this.isSpeaking = false;
        };
        
        utter.onerror = () => {
          this.isSpeaking = false;
        };
        
        this.isSpeaking = true;
        window.speechSynthesis.speak(utter);
      }
    },

    highlightKeywords(text) {
      if (!text) return "";
      
      let cleaned = text.trim()
        .replace(/^\*+\s*/gm, '')
        .replace(/\s*\*+$/gm, '')
        .replace(/\n\s*\*+\s*\n/g, '\n\n');
        
      let result = cleaned.replace(/\*{1,2}([^\*\n]+?)\*{1,2}/g, (match, keyword) => {
        const word = keyword.trim();
        return `<span class="keyword-highlight" data-word="${word}">${word}</span>`;
      });
      
      if (this.keywords && this.keywords.length > 0) {
        this.keywords.forEach(keyword => {
          const englishRegex = new RegExp(`\\b${keyword}\\b`, 'gi');
          result = result.replace(englishRegex, (match) => {
            if (result.includes(`<span class="keyword-highlight" data-word="${keyword}">${match}</span>`)) {
              return match;
            }
            return `<span class="keyword-highlight" data-word="${keyword}">${match}</span>`;
          });
        });
      }
      
      return result;
    },
    
    addKeywordClickListener() {
      this.$nextTick(() => {
        document.querySelectorAll('.keyword-highlight').forEach(el => {
          el.onclick = () => {
            const word = el.getAttribute('data-word');
            if (word) {
              this.$router.push(`/word/${encodeURIComponent(word)}`);
            }
          };
        });
      });
    },
    
    loadPreGeneratedStory() {
      console.log("开始获取预生成故事");
      
      this.templateId = null;
      this.resetStory();
      this.loading = true;
      this.loadingMessage = "获取故事中...";
      
      let userJson = localStorage.getItem("user");
      if (!userJson) {
        this.$message.error("用户信息不存在，请重新登录");
        this.loading = false;
        return;
      }
      
      let user = JSON.parse(userJson);
      
      if (!user.userID) {
        this.$message.error("用户ID不存在，请重新登录");
        this.loading = false;
        return;
      }
      
      const timestamp = new Date().getTime();
      
      request.post("/api/story/pregenerated", null, {
        params: { 
          userID: user.userID,
          _t: timestamp
        }
      })
      .then(res => {
        if (res && res.currentPage) {
          this.handleStoryData(res);
        } else {
          this.displayLines = ["暂无故事内容，请稍后重试。"];
          this.$message.warning(res ? (res.error || "响应数据格式不正确") : "暂无故事内容，请稍后重试");
        }
      })
      .catch(err => {
        console.error("获取预生成故事失败，详细错误:", err);
        this.displayLines = ["获取故事失败，请重试。"];
        this.$message.error(`加载故事失败: ${err.message || "请检查网络连接"}`);
      })
      .finally(() => {
        this.loading = false;
      });
    },
    
    selectChoice(choiceIndex) {
      console.log("用户选择:", choiceIndex);
      this.loading = true;
      this.loadingMessage = "故事发展中...";
      
      let userJson = localStorage.getItem("user");
      let user = JSON.parse(userJson);
      
      const currentPage = this.currentPage;
      
      request.post("/api/story/choice", null, {
        params: {
          userID: user.userID,
          templateId: this.templateId,
          currentPageId: currentPage.id,
          choiceIndex: choiceIndex
        }
      })
      .then(res => {
        if (res && res.page) {
          if (res.keywords) {
            this.keywords = res.keywords;
          }
          
          const newPage = {
            id: res.page.id,
            englishContent: res.page.englishContent,
            chineseContent: res.page.chineseContent,
            sceneImageBase64: res.page.sceneImageBase64,
            choices: res.page.choices || [],
            isEnding: res.page.isEnding || false
          };
          
          this.storyPages.push(newPage);
          this.currentPageIndex = this.storyPages.length - 1;
          this.isStoryEnding = res.isEnding;
          
          this.updateDisplayContent();
          
          if (this.isStoryEnding) {
            this.$message.success("故事已完成！你可以开始新的故事");
          }
        } else {
          this.displayLines = ["无法继续故事，请重试。"];
          this.$message.error("故事分支加载失败");
        }
      })
      .catch(err => {
        console.error("处理选择失败", err);
        this.displayLines = ["处理选择失败，请重试。"];
        this.$message.error("处理选择失败，请重试");
      })
      .finally(() => {
        this.loading = false;
      });
    },
    
    nextPage() {
      if (this.currentPageIndex < this.storyPages.length - 1) {
        this.currentPageIndex++;
        this.updateDisplayContent();
      }
    },
    
    prevPage() {
      if (this.currentPageIndex > 0) {
        this.currentPageIndex--;
        this.updateDisplayContent();
      }
    },
    
    resetStory() {
      this.storyPages = [];
      this.currentPageIndex = 0;
      this.displayLines = [];
      this.chineseTranslation = "";
      this.choices = [];
      this.sceneImage = null;
      this.storyStarted = false;
      this.isStoryEnding = false;
      this.templateId = null;
      this.userProgress = null;
      this.keywords = [];
      this.showTranslation = false;
      this.isSpeaking = false;
      
      // 重置逐词显示相关状态
      this.currentWordIndex = 0;
      this.allWords = [];
      this.isFullyDisplayed = false;
      if (this.typingTimer) {
        clearTimeout(this.typingTimer);
      }
      
      window.speechSynthesis.cancel();
    },
  },
};
</script>

<style>


/* 放在 <style> 不加 scoped 部分 */
.keyword-highlight {
  color: #ff5c7c;
  background: linear-gradient(90deg, #fffbe6 60%, #ffe0f0 100%);
  border-radius: 6px;
  padding: 2px 6px;
  font-weight: bold;
  cursor: pointer;
  transition: box-shadow 0.2s, background 0.2s, color 0.2s, transform 0.2s;
  box-shadow: 0 1px 6px rgba(255,92,124,0.08);
  position: relative;
}
.keyword-highlight:hover {
  background: #ffe0f0;
  box-shadow: 0 2px 12px #ffb3c6;
  color: #d72660;
  transform: scale(1.12) rotate(-2deg);
  animation: keyword-bounce 0.4s;
}
@keyframes keyword-bounce {
  0% { transform: scale(1) rotate(0deg);}
  30% { transform: scale(1.18) rotate(-2deg);}
  60% { transform: scale(0.95) rotate(1deg);}
  100% { transform: scale(1.12) rotate(-2deg);}
}
</style>

<style scoped>
.story-view {
  max-width: 900px;
  margin: 48px auto;
  background: linear-gradient(135deg, #f0f9ff 0%, #dbeafe 100%);
  border-radius: 18px;
  box-shadow: 0 4px 32px rgba(59, 130, 246, 0.13);
  padding: 40px 36px 32px 36px;
  font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  min-height: 480px;
}

.story-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 28px;
}

.story-header h2 {
  font-size: 2.1rem;
  color: #1e40af;
  margin: 0;
  letter-spacing: 2px;
  font-weight: 700;
  display: flex;
  align-items: center;
  flex: 1;
  text-align: center;
}

.button-container {
  display: flex;
  gap: 12px;
}

.refresh-btn {
  background: linear-gradient(90deg, #3b82f6 0%, #1d4ed8 100%);
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 10px 26px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
  transition: background 0.3s, transform 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.refresh-btn:hover {
  background: linear-gradient(90deg, #1d4ed8 0%, #3b82f6 100%);
  transform: translateY(-2px) scale(1.04);
}

.reset-btn {
  background: #64748b;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  background: #475569;
  transform: translateY(-2px);
}

.scene-image-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-bottom: -60px;
  position: relative;
  z-index: 1;
}

.scene-image {
  max-width: 700px;
  width: 100%;
  border-radius: 18px;
  box-shadow: 0 4px 32px rgba(59, 130, 246, 0.13);
}

.scene-image-placeholder {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: -60px;
  position: relative;
  z-index: 1;
  height: 200px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 18px;
  color: #6b7280;
  font-size: 1.1rem;
  font-style: italic;
}

.no-image-notice {
  color: #3b82f6;
  font-size: 1.2rem;
  font-style: italic;
}

.dialogue-box {
  max-width: 700px;
  margin: 0 auto;
  background: #bfdbfe;
  border: 4px dashed #3b82f6;
  border-radius: 32px;
  color: #1e40af;
  padding: 40px 48px 80px 48px; /* 增加底部padding为按钮让出空间 */
  font-family: "Comic Sans MS", "Segoe Script", "PingFang SC", Arial, sans-serif;
  font-size: 1.22rem;
  line-height: 2.1;
  box-shadow: 0 8px 32px rgba(59, 130, 246, 0.19), 0 0 0 8px #f0f9ff inset;
  letter-spacing: 0.5px;
  position: relative;
  overflow: visible;
}

.story-line {
  margin-bottom: 8px;
}

.choices-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-top: 20px;
}

.choice-btn {
  background: rgba(255,255,255,0.12);
  border: 1.5px solid #3b82f6;
  color: #1e40af;
  border-radius: 8px;
  padding: 12px 18px;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s, border 0.2s;
}

.choice-btn:hover {
  background: rgba(255,255,255,0.22);
  border-color: #1d4ed8;
}

.story-ending {
  margin-top: 30px;
  text-align: center;
  font-style: italic;
  color: #3b82f6;
  font-weight: 600;
  padding: 10px;
  border-top: 1px dashed #bfdbfe;
  position: relative;
  z-index: 2;
}

.ending-icon {
  margin-right: 8px;
  font-size: 1.2em;
}

.welcome-message {
  text-align: center;
  color: #1e40af;
  padding: 40px;
}

.welcome-message h3 {
  margin-bottom: 16px;
  font-size: 1.5rem;
}

.welcome-message p {
  margin: 8px 0;
  font-size: 1.1rem;
  opacity: 0.8;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.loading {
  background: white;
  padding: 20px 30px;
  border-radius: 12px;
  color: #1e40af;
  font-size: 1.1rem;
  box-shadow: 0 8px 32px rgba(59, 130, 246, 0.2);
  display: flex;
  align-items: center;
  gap: 12px;
}

.spinner {
  display: inline-block;
  width: 20px;
  height: 20px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #3b82f6;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 翻译文本样式 */
.translation-text {
  margin-top: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.2);
  border: 2px dashed #94a3b8;
  border-radius: 16px;
  color: #475569;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
  font-size: 1.1rem;
  line-height: 1.8;
  white-space: pre-wrap;
  box-shadow: 0 4px 16px rgba(148, 163, 184, 0.1);
}

/* 按钮样式 */
.translation-btn, .speech-btn {
  position: absolute;
  bottom: 16px;
  background: rgba(59, 130, 246, 0.15);
  color: #1e40af;
  border: 1px solid #3b82f6;
  border-radius: 6px;
  padding: 8px 12px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  z-index: 5;
}

.translation-btn {
  right: 16px;
}

.speech-btn {
  right: 140px;
}

.translation-btn:hover, .speech-btn:hover {
  background: rgba(59, 130, 246, 0.25);
  transform: translateY(-2px);
}

/* 页面导航样式 */
.page-navigation {
  position: absolute;
  bottom: 16px;
  left: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  background: rgba(255, 255, 255, 0.15);
  border: 1px solid #3b82f6;
  border-radius: 8px;
  padding: 8px 12px;
  z-index: 5;
}

.page-nav-btn {
  background: rgba(255, 255, 255, 0.2);
  color: #1e40af;
  border: 1px solid #3b82f6;
  border-radius: 6px;
  padding: 6px 12px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 4px;
}

.page-nav-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.page-nav-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-indicator {
  color: #1e40af;
  font-size: 0.9rem;
  font-weight: bold;
  min-width: 60px;
  text-align: center;
}

.restart-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 6px;
  padding: 8px 16px;
  margin-left: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.restart-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.back-btn {
  margin-right: 0;
}

.back-btn:hover {
  color: #1d4ed8;
}

.generate-story-btn {
  background: linear-gradient(90deg, #10b981 0%, #059669 100%);
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 10px 26px;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.3);
  transition: background 0.3s, transform 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

.generate-story-btn:hover {
  background: linear-gradient(90deg, #059669 0%, #10b981 100%);
  transform: translateY(-2px) scale(1.04);
}


</style>